﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
namespace Foundry.Graphics
{
	/// <summary>
	/// Represents a buffer ready to be rendered unto.
	/// </summary>
    public sealed class Renderbuffer : IHandle, IDisposable
    {
        public bool Disposed { get; private set; }
        public int Handle { get; private set; }
        public event EventHandler Disposing;

        public RenderbufferStorage Storage { get; private set; }
        public int Width { get; private set; }
        public int Height { get; private set; }
        public int Samples { get; private set; }

        public Renderbuffer(RenderbufferStorage storage, int samples, int width, int height)
        {
            GraphicsContext.Assert();
            int new_handle;
            GL.GenRenderbuffers(1, out new_handle);
            Handle = new_handle;
            Storage = storage;
            Width = width;
            Height = height;
            Samples = samples;
            MakeCurrent();
            if (samples > 1)
                GL.RenderbufferStorageMultisample(RenderbufferTarget.Renderbuffer, samples, storage, width, height);
            else
                GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, storage, width, height);
            MakeNullCurrent();
        }

        public void MakeCurrent()
        {
            if (Disposed)
                throw new ObjectDisposedException(GetType().FullName);

            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, Handle);
        }
        public void MakeNullCurrent()
        {
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);
        }
        public void Dispose()
        {
            if (Disposing != null)
                Disposing(this, EventArgs.Empty);
            GL.DeleteRenderbuffers(1, new int[] { Handle });
            Handle = 0;
            Disposed = true;
        }
    }
}
